#include "../../source/net.hpp"
#include "../../source/dispacher.hpp"
#include "../../server/Rpc_router.hpp"

void Add(const Json::Value& req,Json::Value& rsp)
{
    LOG(INFO,"进入Add函数");
    int num1 = req["num1"].asInt();
    int num2 = req["num2"].asInt();
    rsp = num1 + num2;

    //LOG(INFO,"rsp: %d",rsp["result"].asInt());

}

int main()
{
    //先是RpcRouter模块，注册回调，以后给dispacher模块的RpcRequest调用
    auto rpc_router = std::make_shared<ns_router::RpcRouter>();

    std::unique_ptr<ns_router::SDescribeFactory> desc_factory(new ns_router::SDescribeFactory());
    desc_factory->Setmethodname("Add");
    desc_factory->Setparas("num1",ns_router::Vtype::INTEGER);
    desc_factory->Setparas("num2",ns_router::Vtype::INTEGER);
    desc_factory->SetResult(ns_router::Vtype::INTEGER);
    desc_factory->SetCb(Add);
    
    rpc_router->RegisterMethod(desc_factory->Build());

    //dispacher模块的回调，绑定RpcRouter模块的RpcRequest处理函数。
    auto dispacher = std::make_shared<ns_dispacher::Dispacher>();

    auto cb = std::bind(&ns_router::RpcRouter::OnRpcRequest,rpc_router.get(),std::placeholders::_1,std::placeholders::_2);
    //注册表注册RpcRouter的对应RpcRequest的方法
    dispacher->Registercb<RpcRequest>(ns_fields::Mtype::RPC_REQ,cb);

    //Server模块的回调是绑定dispacher注册表里的回调方法为回调对象。
    auto msg_cb = std::bind(&ns_dispacher::Dispacher::OnMessage,dispacher.get(),std::placeholders::_1,std::placeholders::_2);
    
    auto server = ns_net::ServerFactory::ServerCreate(8888);
    //start里的onMessage，会处理数据，包括把缓冲区数据根据自己的协议字段构成对应mtype的msg，回调处理时，用的就是对应mtype类型的回调，
    //MessageCallback的第二个参数就是BaseMessage，通过它拿到mtype。
    server->SetMessageCallback(msg_cb);
    server->start();
}